using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MyHomeworkWebAPi.Models.ef;
using MyHomeworkWebAPi.Models.Request;
using MyHomeworkWebAPi.Models.response;
using MyHomeworkWebAPi.Services;

namespace MyHomeworkWebAPi.Controllers
{
    /// <summary>
    /// 消息管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class MessagesController : ControllerBase
    {
        private readonly IMessageServices _messageServices;
        private readonly ILogger<MessagesController> _logger;

        /// <summary>
        /// 构造函数，注入消息服务和日志服务
        /// </summary>
        /// <param name="messageServices">消息服务接口</param>
        /// <param name="logger">日志服务</param>
        public MessagesController(IMessageServices messageServices, ILogger<MessagesController> logger)
        {
            _messageServices = messageServices;
            _logger = logger;
        }

        /// <summary>
        /// 获取所有消息
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetAll()
        {
            var messages = await _messageServices.GetAllAsync();
            return Ok(ApiResponse<List<Message>>.SuccessResponse(messages));
        }

        /// <summary>
        /// 根据ID获取消息
        /// </summary>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetById(Guid id)
        {
            var message = await _messageServices.GetByIdAsync(id);
            if (message == null)
            {
                return NotFound(ApiResponse<Message>.ErrorResponse("消息不存在", 404));
            }
            return Ok(ApiResponse<Message>.SuccessResponse(message));
        }

        /// <summary>
        /// 创建消息
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] MessageCreateRequest request)
        {
            try
            {
                var message = await _messageServices.CreateAsync(request);
                _logger.LogInformation($"Message created successfully for user {request.UserId}");
                return Ok(ApiResponse<Message>.SuccessResponse(message, "消息创建成功"));
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"Failed to create message: {ex.Message}");
                return BadRequest(ApiResponse<Message>.ErrorResponse(ex.Message, 400));
            }
        }

        /// <summary>
        /// 删除消息
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(Guid id)
        {
            var result = await _messageServices.DeleteAsync(id);
            if (!result)
            {
                return NotFound(ApiResponse<bool>.ErrorResponse("消息不存在", 404));
            }
            return Ok(ApiResponse<bool>.SuccessResponse(true, "消息删除成功"));
        }

        /// <summary>
        /// 获取用户的消息列表
        /// </summary>
        [HttpGet("user/{userId}")]
        public async Task<IActionResult> GetByUserId(Guid userId)
        {
            var messages = await _messageServices.GetByUserIdAsync(userId);
            return Ok(ApiResponse<List<Message>>.SuccessResponse(messages));
        }

        /// <summary>
        /// 标记消息为已读
        /// </summary>
        [HttpPut("{id}/read")]
        public async Task<IActionResult> MarkAsRead(Guid id)
        {
            try
            {
                var message = await _messageServices.MarkAsReadAsync(id);
                return Ok(ApiResponse<Message>.SuccessResponse(message, "消息已标记为已读"));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResponse<Message>.ErrorResponse(ex.Message, 400));
            }
        }

        /// <summary>
        /// 获取用户未读消息数量
        /// </summary>
        [HttpGet("unread-count/{userId}")]
        public async Task<IActionResult> GetUnreadCount(Guid userId)
        {
            var count = await _messageServices.GetUnreadCountAsync(userId);
            return Ok(ApiResponse<int>.SuccessResponse(count));
        }
    }
} 